package com.kuaifawu.lwnlawyerclient.Activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.kuaifawu.lwnlawyerclient.Fragment.KWNHomeFragment;
import com.kuaifawu.lwnlawyerclient.Fragment.KWNMySetFragment;
import com.kuaifawu.lwnlawyerclient.Fragment.LWNFeedbackFragment;
import com.kuaifawu.lwnlawyerclient.Fragment.LWNGrowCenterFragment;
import com.kuaifawu.lwnlawyerclient.Fragment.LWNLawyerCenterFragment;
import com.kuaifawu.lwnlawyerclient.Fragment.LWNMyQuestionFragment;
import com.kuaifawu.lwnlawyerclient.Fragment.LWNSaoCodeFragment;
import com.kuaifawu.lwnlawyerclient.Fragment.NavigationDrawerFragment;
import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Lib.KFWActivityCenter;
import com.kuaifawu.lwnlawyerclient.Lib.LWNJsonToData;
import com.kuaifawu.lwnlawyerclient.Lib.ToastView_custom;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_user;
import com.kuaifawu.lwnlawyerclient.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;

import org.json.JSONObject;

/**
 *
 */
public class MainActivity extends ActionBarActivity implements
        NavigationDrawerFragment.NavigationDrawerCallbacks {

    /**
     * 左侧划出抽屉内部fragment
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;
    private KWNHomeFragment fragment_home;
    private LWNMyQuestionFragment fragment_myquestion;
    private LWNFeedbackFragment fragment_feedback;
    private KWNMySetFragment fragment_set;
    private LWNSaoCodeFragment fragment_sao;
    private LWNLawyerCenterFragment fragment_info;
    private LWNGrowCenterFragment fragment_grow;

    /**
     * 存放上次显示在action bar中的title
     * {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;
    private Fragment currentFragment;
    MainActivity activity_self;
    Boolean bool_reload;

    Menu my_menu;
    Boolean bool_messageUnread = false;
    public  int selectId;
    private boolean isSave=false;//防止每次打开页面刷新SharedPreferences里的下标值


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        MobclickAgent.setDebugMode( true );
//        MobclickAgent.openActivityDurationTrack(false);
        Intent intent=getIntent();
        if(intent!=null){
            Bundle bundle=intent.getExtras();
            if(bundle!=null&&bundle.containsKey("isNewLogin")){
                isSave=bundle.getBoolean("isNewLogin");
            }
        }

        selectId=1;
        activity_self = this;
        mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);

            mTitle = getTitle();
                // 设置抽屉
                mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
                fragment_home.LoadDataWithActivity(activity_self);


          bool_reload = false;
        PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.enable();
        mPushAgent.onAppStart();

        String device_token = UmengRegistrar.getRegistrationId(this);
        KFWActivityCenter.getInstance().setMain_activity(this);
        LWNModel_user.getInstance().setString_deviceToken(activity_self, device_token);

        getIsWebLogin();
        getUnReadFromNetwork();
        getLawyerInfoFromNetwork();
        getPopupWindown();
        SharedPreferences settings=getSharedPreferences("index",Context.MODE_PRIVATE);
        int id=settings.getInt("currentIndex",-1);
//        if(id!=-1){
//            setIndexFragment(id);
//            mNavigationDrawerFragment.mDrawerListView.setItemChecked(id,true);
//        }


    }

    //刷新页面
    @Override
    protected void onResume() {
        super.onResume();

        if(bool_reload) {
            if(fragment_home != null){

                //fragment_home.LoadDataWithActivity(activity_self);
            }else if(fragment_myquestion != null){
                //fragment_myquestion.LoadMyQuestionDataWithActivity(activity_self);
            }
        }
        else{
            bool_reload = true;
        }


        MobclickAgent.onResume(this);



    }

    @Override
    protected void onPause() {
        super.onPause();
       MobclickAgent.onPause(this);
    }

    @Override
    public void onNavigationDrawerItemSelected(String title) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        currentFragment = null;
        //currentFragment = fragmentManager.findFragmentByTag(title);

        switch (title){
            case "来问律师-律师版":{
                selectId=1;
               // isSave=true;
                fragment_feedback = null;
                fragment_myquestion = null;
                fragment_set = null;
                fragment_sao = null;
                fragment_info = null;
                fragment_grow = null;

                if(fragment_home == null) {
                    fragment_home = new KWNHomeFragment();
                }
                ft.replace(R.id.fragment_main,fragment_home);
                if(activity_self != null){
                    fragment_home.LoadDataWithActivity(activity_self);
                }

            }break;
            case "我的回答":{
                selectId=2;
                isSave=true;
                fragment_feedback = null;
                fragment_home = null;
                fragment_set = null;
                fragment_sao = null;
                fragment_info = null;
                fragment_grow = null;

                if(fragment_myquestion == null) {
                    fragment_myquestion = new LWNMyQuestionFragment();
                }
                ft.replace(R.id.fragment_main,fragment_myquestion);
                if (activity_self != null){
                    fragment_myquestion.LoadMyQuestionDataWithActivity(activity_self);
                }
            }break;
            case "我的成长":{
                selectId=3;
                isSave=true;
                fragment_feedback = null;
                fragment_home = null;
                fragment_set = null;
                fragment_sao = null;
                fragment_info = null;
                fragment_myquestion = null;
                fragment_grow = null;

                if (fragment_grow == null) {
                    fragment_grow = new LWNGrowCenterFragment();

                }
                ft.replace(R.id.fragment_main, fragment_grow);

            }break;
            case "意见反馈":{
                selectId=4;
                isSave=true;
                fragment_home = null;
                fragment_myquestion = null;
                fragment_set = null;
                fragment_sao = null;
                fragment_info = null;
                fragment_grow = null;

                if(fragment_feedback == null) {
                    fragment_feedback = new LWNFeedbackFragment();
                }
                ft.replace(R.id.fragment_main, fragment_feedback);

            }break;
            case "系统设置":{
                selectId=5;
                isSave=true;
                fragment_home = null;
                fragment_myquestion = null;
                fragment_feedback = null;
                fragment_sao = null;
                fragment_info = null;
                fragment_grow = null;

                if(fragment_set == null){
                    fragment_set = new KWNMySetFragment();
                }
                ft.replace(R.id.fragment_main,fragment_set);
            }break;
            case "扫一扫":{
                isSave=true;
                selectId=6;
                fragment_home = null;
                fragment_myquestion = null;
                fragment_feedback = null;
                fragment_set = null;
                fragment_info = null;
                fragment_grow = null;

                if (fragment_sao == null) {
                    fragment_sao = new LWNSaoCodeFragment();
                    fragment_sao.LoadSaoCodeDataWithActivity(this);
                }
                ft.replace(R.id.fragment_main, fragment_sao);
//                Intent intent= new Intent(MainActivity.this, CaptureActivity.class);
//                startActivityForResult(intent,120);
            }break;
            case "个人中心":{
                selectId=0;
                isSave=true;
                fragment_home = null;
                fragment_myquestion = null;
                fragment_feedback = null;
                fragment_set = null;
                fragment_sao = null;
                fragment_grow = null;

                if (fragment_info == null) {
                    fragment_info = new LWNLawyerCenterFragment();


                }
                ft.replace(R.id.fragment_main, fragment_info);
                if(activity_self!=null){
                    fragment_info.LoadDataWithActivity(activity_self);
                }

            }break;
        }
        if(isSave){
            saveIndex(selectId);
        }
          // ft.addToBackStack(null);
        ft.commitAllowingStateLoss();

        onSectionAttached(title);
    }

    public void onSectionAttached(String title) {
        if(!title.equals("扫一扫")){
            mTitle = title;
        }

    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        my_menu = menu;
        restoreActionBar();
       // getUnReadFromNetwork();
        if(fragment_home != null){
            getMenuInflater().inflate(R.menu.main, menu);
            if (bool_messageUnread) {
                MenuItem refreshItem = menu.findItem(R.id.action_myQuestion);
                refreshItem.setIcon(R.drawable.ic_action_notify_message);
            } else {
                MenuItem refreshItem = menu.findItem(R.id.action_myQuestion);
                refreshItem.setIcon(R.drawable.ic_action_notify);
            }
            return true;
        }
        else if (fragment_info != null) {
            getMenuInflater().inflate(R.menu.menu_lwnlawyer_center, menu);
            return true;
        }
        else if (fragment_feedback != null){
            fragment_feedback.closeKeyBoard();
            return true;
        }
        else {
            return true;
        }
//        if (!mNavigationDrawerFragment.isDrawerOpen()) {
//            getMenuInflater().inflate(R.menu.main, menu);
//            restoreActionBar();
//            return true;
//        }
//        return super.onCreateOptionsMenu(menu);



    }
   private MenuItem hideitem=null;
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        hideitem=item;
        int id = item.getItemId();
        if (id == R.id.action_myQuestion) {
            /* 新建一个Intent对象 */
            Intent intent = new Intent();
            /* 指定intent要启动的类 */
            intent.setClass(activity_self, LWNMessageCenter.class);
            /* 启动一个新的Activity */
            startActivityForResult(intent, 100);
            return true;
        }else if(id == R.id.action_settings){
            Intent intent = new Intent();
            intent.setClass(activity_self, LWNEditProfileActivity.class);
            startActivityForResult(intent,156);
            return true;

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 100: {
                //刷新右上角红点
                getUnReadFromNetwork();
                if(resultCode==500){
                    int index=data.getExtras().getInt("grow");
                    centerSkipGrow(index);
//                    FragmentManager fragmentManager = getSupportFragmentManager();
//                    FragmentTransaction ft = fragmentManager.beginTransaction();
//                    fragment_feedback = null;
//                    fragment_home = null;
//                    fragment_set = null;
//                    fragment_sao = null;
//                    fragment_info = null;
//                    fragment_myquestion = null;
//                    fragment_grow = null;
//                    if (fragment_grow == null) {
//                        fragment_grow = new LWNGrowCenterFragment();
//                    }
//                    Bundle bundle=new Bundle();
//                    bundle.putInt("index",index);
//                    fragment_grow.setArguments(bundle);
//                    ft.replace(R.id.fragment_main, fragment_grow);
//                    ft.commitAllowingStateLoss();
//                    onSectionAttached("我的成长");// mDrawerListView.setItemChecked(position, true);
//                    mNavigationDrawerFragment.mDrawerListView.setItemChecked(3,true);
//                    hideitem.setVisible(false);

                }
            }
            break;
            case 120:
                mNavigationDrawerFragment.mDrawerListView.setItemChecked(selectId,true);
                break;
            case 300:
                if(resultCode==600){
                     finish();
                }
                break;
            case 156:
                if(resultCode==300){
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, LWNLoginActivity.class);
                    startActivity(intent);
                    finish();
                }
                break;
            default: {

            }break;
        }

    }


    /**
     * 获取通知中心的消息条数
     */
    public void getUnReadFromNetwork() {

        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        if(!center.checkNetworkState(activity_self)){
            ToastView_custom toast = new ToastView_custom(activity_self);
            toast.showCustom(activity_self,"检查网络,稍后重试");
//            home_gooddata_refresh.setRefreshing(false);
//            home_gooddata_refresh.setLoading(false);
            return;
        }
        String string_url = center.getInstance().getUnreadMessage(activity_self);
        HttpUtils http = center.getUtils();
        http.send(HttpRequest.HttpMethod.GET,
                string_url,
                new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                        //proDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                            String string_code = jsonObject.getString("code");
                            switch (Integer.parseInt(string_code)) {
                                case 10000: {
                                    String string_data = jsonObject.getString("data");
                                    //restoreActionBar();
                                    int upload = Integer.parseInt(string_data);

                                    if (upload != 0) {
                                        if(fragment_home!=null){
                                            MenuItem refreshItem = my_menu.findItem(R.id.action_myQuestion);
                                            refreshItem.setIcon(R.drawable.ic_action_notify_message);
                                        }

                                        bool_messageUnread = true;
                                    }else{
                                        MenuItem refreshItem = my_menu.findItem(R.id.action_myQuestion);
                                        if(refreshItem!=null){
                                            refreshItem.setIcon(R.drawable.ic_action_notify);
                                        }

                                        bool_messageUnread = false;
                                    }
                                }
                                break;
                                case 10001: {

                                }
                                break;
                                case 10003: {

                                }
                                break;
                                default: {

                                }
                                break;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            //proDialog.dismiss();
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {

                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                }
        );
    }

    //获取律师信息
    public void getLawyerInfoFromNetwork() {
        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        if(!center.checkNetworkState(activity_self)){
            ToastView_custom toast = new ToastView_custom(activity_self);
            toast.showCustom(activity_self,  "检查网络,稍后重试");
//            home_gooddata_refresh.setRefreshing(false);
//            home_gooddata_refresh.setLoading(false);
            return;
        }
        String string_url = center.getInstance().getLawyerInfo(this);
        HttpUtils http = center.getUtils();
        http.send(HttpRequest.HttpMethod.GET,
                string_url,
                new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                        try {
                            JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                            String string_code = jsonObject.getString("code");
                            switch (Integer.parseInt(string_code)) {
                                case 10000: {
                                    JSONObject json_object = jsonObject.getJSONObject("data");
                                    LWNJsonToData.saveLawyerInfoWithJsonString(json_object);
                                }
                                break;
                                case 10001: {

                                }
                                break;
                                case 10003: {

                                }
                                break;
                                default: {

                                }
                                break;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {

                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                }
        );
    }


    /**
     * 在屏幕上添加一个转动的小菊花（传说中的Loading），默认为隐藏状态
     * 注意：务必保证此方法在setContentView()方法后调用，否则小菊花将会处于最底层，被屏幕其他View给覆盖
     *
     * @param activity                    需要添加菊花的Activity
     * @param customIndeterminateDrawable 自定义的菊花图片，可以为null，此时为系统默认菊花
     * @return {ProgressBar}    菊花对象
     */

//        private void createProgressBar(Activity activity, Drawable customIndeterminateDrawable) {
//        // activity根部的ViewGroup，其实是一个FrameLayout
//        FrameLayout rootContainer = (FrameLayout) activity.findViewById(android.R.id.content);
//        // 给progressbar准备一个FrameLayout的LayoutParams
//        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
//                ViewGroup.LayoutParams.WRAP_CONTENT,
//                ViewGroup.LayoutParams.WRAP_CONTENT);
//        // 设置对其方式为：屏幕居中对其
//        lp.gravity = Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL;
//
//        ProgressBar progressBar = new ProgressBar(activity);
//        progressBar.setVisibility(View.GONE);
//        progressBar.setLayoutParams(lp);
//        // 自定义小菊花
//        if (customIndeterminateDrawable != null) {
//            progressBar.setIndeterminateDrawable(customIndeterminateDrawable);
//        }
//        // 将菊花添加到FrameLayout中
//        rootContainer.addView(progressBar);
//        progressBar.setVisibility(View.VISIBLE);

//        DisplayMetrics dm = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(dm);
//        int screenWidth = dm.widthPixels;
//        int screenHeight = dm.heightPixels;
//
//        LinearLayout mProgressLayout = new LinearLayout(this);
//        mProgressLayout.setMinimumWidth(screenWidth);
//        mProgressLayout.setMinimumHeight(screenHeight);
//        mProgressLayout.setBackgroundColor(Color.argb(190, 0, 0, 0));
//        mProgressLayout.setGravity(Gravity.CENTER);
//        mProgressLayout.setOrientation(LinearLayout.HORIZONTAL);
//        FrameLayout.LayoutParams mLayoutParams = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
//                LinearLayout.LayoutParams.WRAP_CONTENT);
//        mLayoutParams.gravity = Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL;
//
//        ProgressBar mProgressBar = new ProgressBar(this);
//        mProgressLayout.addView(mProgressBar, mLayoutParams);
//        TextView mContent = new TextView(this);
//        mContent.setPadding(20,0,0,0);
//        mContent.setText("加载中...");
//        mContent.setTextSize(16);
//        mContent.setTextColor(Color.WHITE);
//
//        mProgressLayout.addView(mContent, mLayoutParams);
//        mProgressLayout.setVisibility(View.VISIBLE);
//        addContentView(mProgressLayout, mLayoutParams);

//        final ProgressDialog proDialog = android.app.ProgressDialog.show(this,"", "加载中，请稍候...");
//        Thread thread = new Thread() {
//            public void run() {
//                try {
//                    sleep(2000);
//                    //程序加载位置
//
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                proDialog.dismiss();//万万不可少这句，否则会程序会卡死。
//            }
//        };
//        thread.start();
//    }
//
//    private void showToast(){
//        DisplayMetrics dm = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(dm);
//        int screenWidth = dm.widthPixels;
//        int screenHeight = dm.heightPixels;
//
//        LayoutInflater inflater = getLayoutInflater();
//        View layout = inflater.inflate(R.layout.toast_custom,
//                (ViewGroup) findViewById(R.id.llToast));
//        ImageView image = (ImageView) layout
//                .findViewById(R.id.tvImageToast);
//        image.setImageResource(R.drawable.success);
//        TextView text = (TextView) layout.findViewById(R.id.tvTextToast);
//        text.setText("登录成功");
//        Toast toast = new Toast(getApplicationContext());
//        toast.setGravity(Gravity.TOP|Gravity.LEFT, screenWidth/2 - 60, screenHeight/2 - 20);
//        //toast.setDuration(Toast.LENGTH_LONG);
//        toast.setView(layout);
//        toast.show();
//    }

    /**
     * 返回键
     * @param keyCode
     * @param event
     * @return
     */
private long firstTime=0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if(fragment_home!=null) {&&fragment_home!=null
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (System.currentTimeMillis() - firstTime > 500) {
                    firstTime = System.currentTimeMillis();
//                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    ToastView_custom toast = new ToastView_custom(activity_self.getApplicationContext());
                    toast.showCustom(activity_self, "再按一次退出程序");
                } else {

//                    Intent home = new Intent(Intent.ACTION_MAIN);
//                    home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//
//                    home.addCategory(Intent.CATEGORY_HOME);
//
//                    startActivity(home);
                    finish();


                }
                return true;
            }

        //}
        return super.onKeyDown(keyCode, event);

        }

    /**
     * 保存下标
     * @param id
     */
     public void saveIndex(int id){
         SharedPreferences settings=getSharedPreferences("index",Context.MODE_PRIVATE);
         SharedPreferences.Editor editor=settings.edit();
         editor.putInt("currentIndex",id);
         editor.commit();
     }

    /**
     * 根据下标设置上次意外退出时的fragment
     */
    private void setIndexFragment(int index){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        currentFragment = null;
        String title="来问律师-律师版";
        switch (index){
            case 1:{
                title="来问律师-律师版";
                selectId=1;
                isSave=true;
                fragment_feedback = null;
                fragment_myquestion = null;
                fragment_set = null;
                fragment_sao = null;
                fragment_info = null;
                fragment_grow = null;

                if(fragment_home == null) {
                    fragment_home = new KWNHomeFragment();
                }
                ft.replace(R.id.fragment_main,fragment_home);
                if(activity_self != null){
                    fragment_home.LoadDataWithActivity(activity_self);
                }

            }break;
            case 2:{
                title="我的回答";
                selectId=2;
                isSave=true;
                fragment_feedback = null;
                fragment_home = null;
                fragment_set = null;
                fragment_sao = null;
                fragment_info = null;
                fragment_grow = null;

                if(fragment_myquestion == null) {
                    fragment_myquestion = new LWNMyQuestionFragment();
                }
                ft.replace(R.id.fragment_main,fragment_myquestion);
                if (activity_self != null){
                    fragment_myquestion.LoadMyQuestionDataWithActivity(activity_self);
                }
            }break;
            case 3:{

                title="我的成长";
                selectId=3;
                isSave=true;
                fragment_feedback = null;
                fragment_home = null;
                fragment_set = null;
                fragment_sao = null;
                fragment_info = null;
                fragment_myquestion = null;
                fragment_grow = null;

                if (fragment_grow == null) {
                    fragment_grow = new LWNGrowCenterFragment();
                }
                ft.replace(R.id.fragment_main, fragment_grow);
            }break;
            case 4:{
                title="意见反馈";
                selectId=4;
                isSave=true;
                fragment_home = null;
                fragment_myquestion = null;
                fragment_set = null;
                fragment_sao = null;
                fragment_info = null;
                fragment_grow = null;

                if(fragment_feedback == null) {
                    fragment_feedback = new LWNFeedbackFragment();
                }
                ft.replace(R.id.fragment_main, fragment_feedback);

            }break;
            case 5:{
                title="系统设置";
                selectId=5;
                isSave=true;
                fragment_home = null;
                fragment_myquestion = null;
                fragment_feedback = null;
                fragment_sao = null;
                fragment_info = null;
                fragment_grow = null;

                if(fragment_set == null){
                    fragment_set = new KWNMySetFragment();
                }
                ft.replace(R.id.fragment_main,fragment_set);
            }break;
            case 6:{
                title="扫一扫";
                selectId=6;
                isSave=true;
                fragment_home = null;
                fragment_myquestion = null;
                fragment_feedback = null;
                fragment_set = null;
                fragment_info = null;
                fragment_grow = null;

                if (fragment_sao == null) {
                    fragment_sao = new LWNSaoCodeFragment();
                    fragment_sao.LoadSaoCodeDataWithActivity(this);
                }
                ft.replace(R.id.fragment_main, fragment_sao);
//                Intent intent= new Intent(MainActivity.this, CaptureActivity.class);
//                startActivityForResult(intent,120);
            }break;
            case 0:{
                title="个人中心";
                selectId=0;
                isSave=true;
                fragment_home = null;
                fragment_myquestion = null;
                fragment_feedback = null;
                fragment_set = null;
                fragment_sao = null;
                fragment_grow = null;

                if (fragment_info == null) {
                    fragment_info = new LWNLawyerCenterFragment();
                }
                ft.replace(R.id.fragment_main, fragment_info);

            }break;
        }

        if(isSave){
            saveIndex(selectId);
        }
        //ft.addToBackStack(null);
        ft.commitAllowingStateLoss();

        onSectionAttached(title);
    }


    /**
     * 弹出新手引导窗口
     */
    private PopupWindow popupWindow=null;
    private View parent=null;
    private void getPopupWindown(){

        View pView=getLayoutInflater().inflate(R.layout.popu_view_layout,null);
        popupWindow=new PopupWindow(pView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,true);

        popupWindow.setOutsideTouchable(true);

        popupWindow.setFocusable(true);
        parent=this.getWindow().getDecorView();
        pView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(popupWindow.isShowing()){

                    popupWindow.dismiss();
                    isOpen=false;
                    preferences=getSharedPreferences("isopen",Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor=preferences.edit();
                    editor.putBoolean("open", isOpen);
                    editor.commit();
                }
            }
        });


    }


    private Boolean isOpen=true;
    private SharedPreferences preferences=null;
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        preferences=getSharedPreferences("isopen", Context.MODE_PRIVATE);
        isOpen= preferences.getBoolean("open",true);
       if(isOpen){
            popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        isOpen=false;
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Intent intent=null;

            switch (msg.what){
                case 1:
//                    intent=new Intent(MainActivity.this,LWNLoginActivity.class);
//                    startActivity(intent);
//                    finish();

                    break;
                case 2:


                    break;

                case 3:
                    intent=new Intent(MainActivity.this,LWNLognWebActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putString("code","123");
                    intent.putExtras(bundle);
                    startActivityForResult(intent,300);


                    break;
            }

        }
    };

    /**
     * 判断登录情况
     */

    private void getIsWebLogin(){
        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        String url=center.getIsWebLogn(MainActivity.this);
        HttpUtils httpUtils=center.getUtils();
        httpUtils.configDefaultHttpCacheExpiry(0*0);
        httpUtils.send(HttpRequest.HttpMethod.GET,url,new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                try{
                    JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                    String string_code = jsonObject.getString("code");
                    String string_msg = jsonObject.getString("msg");
                    switch (String.valueOf(string_code)){
                        case "10000":
                            handler.sendEmptyMessage(3);
                            break;
                        case "10003":
                           // handler.sendEmptyMessage(1);
//                            Intent intent=null;
//                            intent=new Intent(MainActivity.this,LWNLoginActivity.class);
//                            startActivity(intent);
//                            finish();
                            break;
                        default:
                            handler.sendEmptyMessage(2);
                            break;
                    }

                } catch (Exception e){
                    e.printStackTrace();
                }

            }
            @Override
            public void onFailure(HttpException e, String s) {

            }
        });

    }

    /**
     *点击个人中心跳转至成长的页面
     */
 public  void centerSkipGrow(int index){
    // int index=1;
     FragmentManager fragmentManager = getSupportFragmentManager();
     FragmentTransaction ft = fragmentManager.beginTransaction();
     fragment_feedback = null;
     fragment_home = null;
     fragment_set = null;
     fragment_sao = null;
     fragment_info = null;
     fragment_myquestion = null;
     fragment_grow = null;
     if (fragment_grow == null) {
         fragment_grow = new LWNGrowCenterFragment();
     }
     Bundle bundle=new Bundle();
     bundle.putInt("index",index);
     fragment_grow.setArguments(bundle);
     ft.replace(R.id.fragment_main, fragment_grow);
     ft.commitAllowingStateLoss();
     onSectionAttached("我的成长");
     mNavigationDrawerFragment.mDrawerListView.setItemChecked(3,true);
     MenuItem item=my_menu.getItem(0);
     item.setVisible(false);
    // hideitem.setVisible(false);



      }




}


